<?php

namespace App\Kuafu\Order\Service;

use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Model\OrderCouponExtSplitModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderCouponSplitModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use Illuminate\Support\Facades\Log;

/**
 * 订单反结账操作
 *
 * Class OrderPayService
 * @package App\Kuafu\Order\Service
 */
class OrderRefund extends OrderBaseSplitService
{

    /**
     * 更新退款详情
     */
    public function updateOrderRefundV2()
    {
        $order = $this->getOrderInfo();

        // 支付总流水
        $totalPay = OrderPay::getOrderPayStreamPrice($this->orderId);
        // 支付总流水
        $totalPayList = OrderPay::getOrderPayStreamPrice($this->orderId, [], PayStreamModel::PAID_IN_ALL);
        // 订单总退款金额
        $totalRefund = self::getOrderRefundPrice($this->orderId, [], PayStreamModel::PAID_IN_YES);
        // 订单总退款流水
        $totalRefundList = self::getOrderRefundPrice($this->orderId);
        // 订单实收 = 总支付 - 总退款
        $totalPayPrice = $totalPay - $totalRefund;
        // 获取订单应付金额 =
        // 如果存在退款金额 就有反结账状态
        if ($totalRefundList == 0) {
            return;
        }

        // 判断 realpay 是否为 0

        if ($totalPayList - $totalRefundList == 0 && $order['originalPrice'] == 0) {
            $refundStatus = CodeEnum::ORDER_REFUND_STATUS_ALL;
        } else {
            $refundStatus = CodeEnum::ORDER_REFUND_STATUS_PART;
        }

        Log::channel('order')->info('OrderRefund_updateOrderRefund', [
            'orderId'          => $this->orderId,
            'totalPayPrice'    => $totalPayPrice,
            'totalPay'         => $totalPay,
            'totalRefund'      => $totalRefund,
            '$totalRefundList' => $totalRefundList,
            'refundStatus'     => $refundStatus
        ]);

        $order->payPrice     = $totalPayPrice;
        $order->realPayPrice = $order->payPrice + $order->couponCostPrice;
        $order->refundStatus = $refundStatus;
        $order->refundMoney  = $totalRefundList;


//        dump($order->payPrice, $order->realPayPrice, $order->refundStatus, $order->refundMoney);
        $order->save();
    }


    /**
     * 更新退款详情
     */
    public function updateOrderRefund()
    {
        $order = $this->orderInfo;
        // 支付总金额
        $totalPay = $this->getOrderTotalPrice();
        // 订单总退款金额
        $totalRefund = self::getOrderRefundPrice($this->orderId);
        // 订单实收 = 总支付 - 总退款
        $totalPayPrice = $totalPay - $totalRefund;

        if ($totalPayPrice == 0) {
            $refundStatus = CodeEnum::ORDER_REFUND_STATUS_ALL;
        } else {
            $refundStatus = CodeEnum::ORDER_REFUND_STATUS_PART;
        }

        Log::channel('order')->info('OrderRefund_updateOrderRefund', [
            'totalPayPrice' => $totalPayPrice,
            'totalPay'      => $totalPay,
            'totalRefund'   => $totalRefund,
        ]);

        $order->payPrice     = $totalPayPrice;
        $order->refundStatus = $refundStatus;
        $order->refundMoney  = $totalRefund;

        $order->save();
    }


    /**
     * 获取订单总退款流水总额
     *
     * @param string $orderId
     * @return int
     */
    public static function getOrderRefundPrice(
        string $orderId,
        array $refundChannel = [],
        $isPaidIn = PayStreamModel::PAID_IN_ALL
    ): int {
        // 查原始订单的支付记录
        $payStreams = PayStreamModel::getPayRefundsByOrderId((int)$orderId, '', $refundChannel, $isPaidIn);

        // 已赎回金额
        $hasRefundMoney = 0;
        foreach ($payStreams as $pay) {
            if ($pay->refundStreamRel->count()) {
                $hasRefundMoney += $pay->refundStreamRel->sum('refundPrice');
            }
        }

        return $hasRefundMoney;
    }


    /**
     * 获取 订单总支付优惠价格
     *
     * @return int
     */
    public function getOrderPayExtCoupon(): int
    {
        return OrderCouponExtSplitModel::suffix($this->shopId)->query()
                                       ->where('orderId', $this->orderId)
                                       ->where('couponExtStatus',
                                           CouponExtEnum::COUPON_STATUS_USED)
                                       ->sum('couponExtCostPrice');
    }

    /**
     * 获取 订单总支付优惠价格
     *
     * @return int
     */
    public function getCouponCostPrice(): int
    {
        return OrderCouponSplitModel::suffix($this->shopId)->query()
                                    ->where('orderId', $this->orderId)
                                    ->where('status',
                                        OrderCouponSplitModel::STATUS_USED)
                                    ->sum('couponCostPrice');

    }

    /**
     * 获取订单总实收 [ 支付宝 + 微信 + 美团 + 优惠券成本金额]
     */
    public function getOrderTotalPrice()
    {
        $price = OrderPay::getOrderPayStreamPrice($this->orderId);

        return $price + $this->getOrderPayExtCoupon() + $this->getCouponCostPrice();
    }
}
